package com.fly.show.web;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api(tags = "图片接口")
@Slf4j
@Controller
@RequestMapping("/show")
public class PicController
{
    Resource[] resources;
    
    List<Resource> resourceList = new ArrayList<>();
    
    /**
     * FIFO
     */
    private Queue<Integer> quque = new ConcurrentLinkedQueue<>();
    
    @PostConstruct
    private void init()
    {
        try
        {
            resources = new PathMatchingResourcePatternResolver().getResources(ResourceUtils.CLASSPATH_URL_PREFIX + "data/pic/**/*.jpg");
            Arrays.stream(resources).forEach(image -> {
                resourceList.add(image);
                log.info("add pic: {}", image.getFilename());
            });
        }
        catch (IOException e)
        {
            log.error(e.getMessage(), e);
        }
    }
    
    @GetMapping("/index")
    public String index()
    {
        return "index.html";
    }
    
    @ApiOperation("图片")
    @ResponseBody
    @GetMapping(value = {"/pic", "/img"}, produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] showPic1(HttpServletResponse response)
        throws IOException
    {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(createImage(), "jpg", os);
        return os.toByteArray();
    }
    
    /**
     * createImage 生成图片
     * 
     * @return
     * @throws IOException
     * @see [类、类#方法、类#成员]
     */
    private BufferedImage createImage()
        throws IOException
    {
        if (resources.length < 4)
        {
            log.info("############### 请在[resources/data/pic/]目录放入不少于4张jpg图片 ###############");
            return new BufferedImage(400, 400, BufferedImage.TYPE_BYTE_GRAY);
        }
        // 取图片
        int index = getIndex(resources.length);
        return ImageIO.read(resources[index].getInputStream());
    }
    
    private byte[] lock = new byte[0];
    
    private int getIndex(int max)
    {
        int index;
        if (quque.size() < 3)
        {
            synchronized (lock)
            {
                // 集中1次生成，多次使用
                while (quque.size() < max)
                {
                    index = RandomUtils.nextInt(0, max);
                    if (!quque.contains(index))
                    {
                        quque.add(index);
                    }
                }
            }
            log.info("{}", quque);
        }
        index = quque.poll();
        log.info("{} <= {} , ", index, quque);
        return index;
    }
}
